import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'dart:async';
import 'package:flutter/services.dart' show rootBundle;

final parser = RSAKeyParser();

/*
 * 这里有一个坑   windows 里面  换行  \r\n  
 * linux  换行  \n
 **/
class EncryptHelper {
  static Future<String> encode(String src) async {
    String publicKeyString =
        await rootBundle.loadString('assets/keys/public_key.pem');
    String rsaPublic =
        "-----BEGIN PUBLIC KEY-----\n$publicKeyString\n-----END PUBLIC KEY-----";
    RSAPublicKey publicKey = parser.parse(rsaPublic) as RSAPublicKey;
    final encrypter = Encrypter(RSA(publicKey: publicKey));
    return encrypter.encrypt(src).base64;

    /*var directory = await getApplicationDocumentsDirectory();
        File file = new File('assets/keys/public_key.pem');
    if(!file.existsSync()) {
      print('文件不存在');
      file.createSync();
    }
    var publicKey = await parseKeyFromFile('${directory.path}/keys/public_key.pem');

    final encrypter = Encrypter(RSA(publicKey: publicKey));
    final res = encrypter.encrypt(src).base16.toUpperCase();
    return res;*/
  }

  static Future<String> decode(String decoded) async {
    String privateKeyString =
        await rootBundle.loadString('keys/private_key.pem');
    privateKeyString = privateKeyString.replaceAll("\r", "");
    final privateKey = parser.parse(privateKeyString) as RSAPrivateKey;
    final encrypter = Encrypter(RSA(privateKey: privateKey));
    return encrypter.decrypt(Encrypted.fromBase64(decoded));
  }
}
